package com.lagou.edu.listener;

import com.lagou.edu.mapper.OrderInfoMapper;
import com.lagou.edu.mapper.WarehouseMapper;
import com.lagou.edu.model.OrderInfo;
import com.lagou.edu.model.Warehouse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * @author xh
 * @createTime 2021年6月14 13:59.
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    WarehouseMapper warehouseMapper;
    @Autowired
    StringRedisTemplate redisTemplate;


    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {

        String expireKey = message.toString();

        if (expireKey.startsWith("order:")) {

            Integer orderId = Integer.valueOf(expireKey.replace("order:", ""));

            OrderInfo orderInfo = orderInfoMapper.selectByOrderId(orderId);
            orderInfo.setStatus(2);
            orderInfoMapper.updateStatus(orderInfo);
            System.out.println("订单失效，库存还原+1");
            Warehouse warehouse = warehouseMapper.selectByPrimaryKey(orderInfo.getCommodity());
            warehouse.setNum(warehouse.getNum() + 1);
            warehouseMapper.updateNum(warehouse);
            redisTemplate.opsForValue().increment("num", 1);//库存加1个
        }
    }

}

